function X = blocks2img(Y, nums, X_size, border_size)
% Mordecai Lee, 2017-11-30, Thu, 22:52:05

if length(X_size) == 1, X_size = X_size([1 1]); end
if length(border_size) == 1, border_size = border_size([1 1]); end

if length(nums) > 1
    pp = 0;
    X = cell(1, length(nums));
    for i = 1 : length(nums)
        pp = pp(end)+1 : pp(end)+nums(i);
        X{i} = srimg.blocks2img(Y(:,:,pp), [], X_size(i, :), border_size);
    end
    return
end

Y_size = size(Y);
block_size = Y_size(1 : 2);
border_size(X_size <= block_size) = 0;
if all(border_size == 0)
    X = Y; return
end

block_stride = block_size - 2*border_size;
% block_num = ceil(X_size ./ block_stride);
% finalsep_size = block_stride .* (block_num-2) + block_size - (X_size - block_size);
block_num = ceil((X_size-block_size) ./ block_stride) + 1;
finalsep_size = block_stride .* (block_num-1) + block_size - X_size + border_size;

X = zeros(X_size);

zz = 0;  pp = 0;
for ri = 1 : block_num(1)
    switch ri
        case 1
            rr = 1 : block_size(1)-border_size(1);
        case block_num(1)
            rr = finalsep_size(1)+1 : block_size(1);
        otherwise
            rr = border_size(1)+1 : block_size(1)-border_size(1);
    end
    zz = zz(end)+1 : zz(end)+block_num(2);
    
    a = Y(rr, 1 : end-border_size(2), zz(1));  b = []; c = [];
    
    if border_size(2) > 0
        b = Y(rr, border_size(2)+1 : end-border_size(2), zz(2 : end-1));
        b = reshape(b, size(b, 1), []);
    end
    
    if finalsep_size(2) > 0
        c = Y(rr, finalsep_size(2)+1 : end, zz(end));
    end
    
    pp = pp(end)+1 : pp(end)+length(rr);
    % disp(pp([1 end]))
    X(pp, :) = [a b c];
end
return